package com.xbongbong.pro.statistic.service.result;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartI18Constant;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.IndicatorRuleEnum;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.enums.ValueTypeEnum;
import com.xbongbong.pro.statistic.pojo.vo.ProductInfoVO;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.StatisticResultDTO;
import com.xbongbong.pro.statistic.result.pojo.dto.StatisticResultInfoDTO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.pro.statistic.through.pojo.dto.ThroughDTO;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.service.toolbox.help.ProductHelp;
import com.xbongbong.saas.service.toolbox.help.ScriptHelp;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 生产单相关统计
 *
 * @author 徐俊杰
 * @version v1.0
 * @date 2019/3/14 13:41
 * @since v1.0
 */
@Service
public class JxcProductionOrderResult extends ChartResultParentService implements ChartResultSystem {
    @Resource
    private ProductHelp productHelp;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private SpecificationModel specificationModel;

    @Override
    public Object getTarget(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum) {
            case PRODUCTION_ORDER_ADD_CHART:
                return productionOrderAddChart(chartResultPojo, chartResultDetailVO);
            case PRODUCTION_ORDER_COMPLETE_CHART:
                return productionOrderCompleteChart(chartResultPojo, chartResultDetailVO);
            case PRODUCTION_ORDER_FINISHED_CHART:
                return productionOrderFinishedChart(chartResultPojo, chartResultDetailVO);
            default:
                break;
        }
        return null;
    }

    @Override
    public Object getValueTarget(ChartResultPojo chartResultPojo) throws XbbException {
        return null;
    }

    /**
     * 生产单新增量
     *
     * @param chartResultPojo     corpid, userIdIn, startTime, endTime
     * @param chartResultDetailVO 结果
     * @return java.lang.Object
     * @throws XbbException
     * @author 徐俊杰
     * @date 2019/3/14 14:21
     * @since v1.0
     */
    public Object productionOrderAddChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ElasticAggsPojo elasticAggsPojo = productionOrderAdd2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE);
        ThroughDTO throughDTO = new ThroughDTO(chartResultPojo, chartResultPojo.getSystemCodeEnum());
        //是否画入表格内 0否1是
        Integer tableFlag = 1;
        String legend = I18nMessageUtil.getMessage(I18nStringConstant.PRODUCT_ORDER_ADD_NUMBER);
        String unit = systemChartHelp.getUnit(I18nMessageUtil.getMessage(CommonConstant.EACH));
        Boolean totalFlag = true;
        String valueTitle = I18nMessageUtil.getMessage(ChartI18Constant.TOTAL_NUMBER_NEW_PRODUCTION_ORDERS);
        return systemChartHelp.packageResult4One(elasticAggsPojo, chartResultPojo, chartResultDetailVO, throughDTO, tableFlag, legend, unit, totalFlag, valueTitle);
    }

    /**
     * 生产单完成情况
     *
     * @param chartResultPojo     corpid, userIdIn, startTime, endTime
     * @param chartResultDetailVO 结果
     * @return java.lang.Object
     * @throws XbbException
     * @author 徐俊杰
     * @date 2019/3/26 14:24
     * @since v1.0
     */
    public Object productionOrderCompleteChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        StatisticResultDTO statisticResultDto = getResultCountOne(chartResultPojo);
        //右侧展示总数
        statisticResultDto.setTotalFlag(true);
        statisticResultDto.setValueTitle(I18nMessageUtil.getMessage(ChartI18Constant.TOTAL_NUMBER_COMPLETED_PRODUCTION_ORDERS));
        chartResultDetailVO = systemChartHelp.packageResult(statisticResultDto, chartResultPojo, chartResultDetailVO);
        return chartResultDetailVO;
    }

    /**
     * 生产成品分析
     *
     * @param chartResultPojo     corpid, categoryId, userIdIn, page, pageSize
     * @param chartResultDetailVO 回参
     * @return java.lang.Object
     * @throws XbbException findScroll查询抛出异常
     * @author 徐俊杰
     * @date 2019/3/31 14:13
     * @since v1.0
     */
    public Object productionOrderFinishedChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        Integer page = chartResultPojo.getPage();
        Integer pageSize = chartResultPojo.getPageSize();
        String corpid = chartResultPojo.getCorpid();
        String unit = chartResultPojo.getUnit();
        //获取生产单关联成品id：已经限制过计划完成时间、负责人的生产单ids
        List<PaasFormDataEntityExt> productionOrderList = formHelp.getProductionOrderListByTeam(chartResultPojo);
        Set<Long> productionOrderIdIn = new HashSet<>();
        Set<Long> productIdIn = new HashSet<>();
        String productIdAttr = ProductionOrderEnum.PRODUCT.getAttr();
        String numAttr = ProductionOrderEnum.PRODUCT_NUM.getAttr();
        String instockNumAttr = ProductionOrderEnum.PRODUCT_INSTOCK_NUM.getAttr();
        //产品id--生产成品数量
        Map<Long, Double> idNumMap = new HashMap<>(productionOrderList.size());
        //产品id--成品已经入库数量
        Map<Long, Double> idInstockNumMap = new HashMap<>(productionOrderList.size());
        for (PaasFormDataEntityExt entity : productionOrderList) {
            JSONObject data = entity.getData();
            productionOrderIdIn.add(entity.getDataId());
            if (data == null) {
                continue;
            }
            //关联产品id，存的是数组格式，因此getJSONArray
            List<Long> pidList = JSONArray.parseArray(data.getString(productIdAttr), Long.class);
            if (pidList == null) {
                continue;
            }
            Double num = data.getDoubleValue(numAttr);
            Double instockNum = data.getDoubleValue(instockNumAttr);
            for (Long productId: pidList){
                if (productId == null) {
                    continue;
                }
                productIdIn.add(productId);
                Double valueNum = idNumMap.get(productId);
                Double valueInstockNum = idInstockNumMap.get(productId);

                valueNum = (valueNum == null) ? num : valueNum + num;
                valueInstockNum = (valueInstockNum == null) ? instockNum : instockNum + valueInstockNum;
                idNumMap.put(productId, valueNum);
                idInstockNumMap.put(productId, valueInstockNum);
            }
        }
        //获取产品Id-成品入库总成本map
        Map<Long, Double> productIdCostSumMap = getProductIdCostSumMap(chartResultPojo, productionOrderIdIn);
        //限制产品ids
        BoolQueryBuilder productQueryBuilder = chartQueryHelp.boolQueryBuilder4BaseByIds(corpid, null, productIdIn, IndexTypeEnum.IDX_SAAS_PRODUCT);
        //处理分类筛选
        //分类id-分类名map
        Map<Long, String> categoryIdNameMap = productHelp.setCategoryQuery(corpid, productQueryBuilder, chartResultPojo.getRefId());
        //分页查询
        XbbAggregatedPage<ProductInfoVO> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_PRODUCT, productQueryBuilder, ProductInfoVO.class, null, page, pageSize, null);
        List<ProductInfoVO> productInfoVoList = new ArrayList<>();
        int rowCounts = 0;
        if (esEntities != null) {
            productInfoVoList = esEntities.getContent();
            rowCounts = (int) esEntities.getTotalElements();
        }
        PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, page, pageSize, PageConstant.DEFAULT_PAGE_SIZE_SMALL);

        //封装产品销量表数据
        List<List<ResultDataTableVO>> tableData = formatProductSaleTableData(corpid, idNumMap, idInstockNumMap, productIdCostSumMap, categoryIdNameMap, productInfoVoList, chartResultPojo);
        ResultTableVO table = new ResultTableVO();
        table.setPageHelper(pageHelper);
        List<String> title = Arrays.asList(String.format(I18nMessageUtil.getMessage(ChartI18Constant.PRODUCTION_ORDER_FINISHED_CHART_TITLE), unit).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setData(tableData);
        table.setTableName(IndicatorRuleEnum.PRODUCTION_ORDER_FINISHED.getName());
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    /**
     *
     * @param corpid
     * @param idNumMap
     * @param idInstockNumMap
     * @param idCostSumMap
     * @param categoryIdNameMap
     * @param productInfoVoList
     * @param chartResultPojo
     * @return java.util.List<java.util.List<com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO>>
     * @throws
     * @author zcp
     * @date 2019/4/10 21:34
     * @since v1.0
     * @version v1.0
     */
    private List<List<ResultDataTableVO>> formatProductSaleTableData(String corpid, Map<Long, Double> idNumMap, Map<Long, Double> idInstockNumMap, Map<Long, Double> idCostSumMap, Map<Long, String> categoryIdNameMap, List<ProductInfoVO> productInfoVoList, ChartResultPojo chartResultPojo) throws XbbException {
        Set<Long> parentIdIn = new HashSet<>();
        Set<Long> categoryIdIn = new HashSet<>();
        Integer numFormat = chartResultPojo.getNumFormat();
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(numFormat);
        String categoryIdAttr = ProductEnum.CATEGORY_ID.getAttr();
        String parentIdAttr = ProductEnum.PARENT_ID.getAttr();
        for (ProductInfoVO product : productInfoVoList) {
            JSONObject data = JsonHelperUtil.getJSONObject(product.getData());
            categoryIdIn.add(data.getLong(categoryIdAttr));
            parentIdIn.add(data.getLong(parentIdAttr));
        }
        //父级产品id--产品编号map
        Map<Long, String> parentIdNoMap = formHelp.getParentIdNoMap(corpid, parentIdIn);
        //当未筛选分类时，没有去查分类categoryIdNameMap的size为0，所以要在此处查询一次需要的分类信息
        if (categoryIdNameMap.size() == 0) {
            List<ProductCategoryEntity> categoryList = productCategoryModel.getProductCategoryListByIdIn(corpid, categoryIdIn);
            for (ProductCategoryEntity entity : categoryList) {
                categoryIdNameMap.put(entity.getId(), entity.getName());
            }
        }

        String nameAttr = ProductEnum.NAME.getAttr();
        String specificationAttr = ProductEnum.SPECIFICATION_LINK_TEXT.getAttr();
        String unitAttr = ProductEnum.UNIT.getAttr();
        //获取启用的产品单位
        Map<String, String> unitMap = formHelp.getProductUnitItemMap(corpid);
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        for (ProductInfoVO entityExt : productInfoVoList) {
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long productId = entityExt.getId();
            String categoryName = categoryIdNameMap.get(data.getLongValue(categoryIdAttr));
            categoryName = StringUtil.isEmpty(categoryName) ? "" : categoryName;
            String unit = unitMap.getOrDefault(data.getString(unitAttr), "");
            double sumProductNum = idNumMap.getOrDefault(productId, 0D);
            double sumProductInstockNum = idInstockNumMap.getOrDefault(productId, 0D);
            double sumCost = idCostSumMap.getOrDefault(productId, 0D);
            List<ResultDataTableVO> voList = new ArrayList<>();
            voList.add(new ResultDataTableVO(formHelp.getProductNo(parentIdNoMap, data), null));
            voList.add(new ResultDataTableVO(data.getString(nameAttr), null));
            String specification = specificationModel.joinSpecification(data.getString(specificationAttr));
            voList.add(new ResultDataTableVO(specification, null));
            voList.add(new ResultDataTableVO(categoryName, null));
            voList.add(new ResultDataTableVO(unit, null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(sumProductNum), null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(sumProductInstockNum), null));
            voList.add(new ResultDataTableVO(ChartResultUtil.formatVal2Thousands(BigDecimal.valueOf(sumCost), numFormatEnum), null));
            tableData.add(voList);
        }
        return tableData;
    }

    /**
     * 封装生产单完成情况的统计结果
     *
     * @param chartResultPojo 参数pojo
     * @return com.xbongbong.pro.statistic.pojo.dto.StatisticResultDTO
     * @throws XbbException
     * @author 徐俊杰
     * @date 2019/3/26 14:19
     * @since v1.0
     */
    private StatisticResultDTO getResultCountOne(ChartResultPojo chartResultPojo) throws XbbException {
        List<String> legendList = Arrays.asList(I18nMessageUtil.getMessage(ChartI18Constant.PRODUCTION_ORDER_COMPLETE_CHART_CONTENT).split(","));
        String unit = systemChartHelp.getUnit(I18nMessageUtil.getMessage(CommonConstant.EACH));
        String unit1 = systemChartHelp.getUnit("%");
        List<String> unitList = Arrays.asList(unit, unit, unit,unit1, unit1);
        //所有已完成
        Script script = null;
        ElasticAggsPojo all = productionOrderComplete2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE, script);
        String planTime = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.PLAN_TIME);
        String completeTime = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.COMPLETE_TIME);
        /*
        完成时间为空或计划时间 >= 完成时间为未超时
        "doc['data.date_1'].value - doc['data.date_2'].value >= 0"
         */
        script = ScriptHelp.minusFilter4Egt(planTime, completeTime, "0");
        ElasticAggsPojo notOverTime = productionOrderComplete2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE, script);
        //未超时比例
        ElasticAggsPojo notOverTimeRate = systemChartHelp.getRateResult4Int(notOverTime, all);
        /*
        已完成超时
        "doc['data.date_1'].value - doc['data.date_2'].value < 0"
         */
        script = ScriptHelp.minusFilter4Lt(planTime, completeTime, "0");
        ElasticAggsPojo overTime = productionOrderComplete2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE, script);
        //超时比例
        ElasticAggsPojo overTimeRate = systemChartHelp.getRateResult4Int(overTime, all);

        ///////////////////////////////
//        List<StatisticResultInfoDTO> statisticResultInfoDtoList = systemChartHelp.getInfoDtos4MomYoy(chartResultPojo, legendList, unitList, all, notOverTime, overTime, notOverTimeRate, overTimeRate);
        //全部
        ThroughDTO throughDtoAll = new ThroughDTO(chartResultPojo, SystemCodeEnum.PRODUCTION_ORDER_TOTAL);
        //按时
        ThroughDTO throughDtoIntime = new ThroughDTO(chartResultPojo, SystemCodeEnum.PRODUCTION_ORDER_FINISH_INTIME);
        //超时
        ThroughDTO throughDtoDelay = new ThroughDTO(chartResultPojo, SystemCodeEnum.PRODUCTION_ORDER_FINISH_DELAY);
        //是否画入表格内 0否1是
        Integer tableFlag = 1;
        //分别采用两个不同单位的y轴，默认为yAxisIndex: 0，当为1时，代表另外一个y坐标轴
        Integer yAxisIndex = 0;
        //1隐藏，0不隐藏
        Integer hide = 0;
        //--------------------y轴左侧--------------------
        //生产单总数
        StatisticResultInfoDTO allStatisticResultInfoDto = new StatisticResultInfoDTO(throughDtoAll, tableFlag, yAxisIndex, hide, legendList.get(0), unitList.get(0), all);
        //按时完成生产单数
        StatisticResultInfoDTO inTimeStatisticResultInfoDto = new StatisticResultInfoDTO(throughDtoIntime, tableFlag, yAxisIndex, hide, legendList.get(1), unitList.get(1), notOverTime);
        //超时完成生产单数
        StatisticResultInfoDTO delayStatisticResultInfoDto = new StatisticResultInfoDTO(throughDtoDelay, tableFlag, yAxisIndex, hide, legendList.get(2), unitList.get(2), overTime);
        //--------------------y轴右侧--------------------
        yAxisIndex = 1;
        hide = 1;
        //环比、同比，必须强制置为折线类型
        StatisticResultInfoDTO inTimeStatisticResultInfoDtoRate = new StatisticResultInfoDTO(throughDtoIntime, tableFlag, yAxisIndex, hide, legendList.get(3), unitList.get(3), notOverTimeRate);
        inTimeStatisticResultInfoDtoRate.setChartType(ChartTypeEnum.LINE_CHART.getCode());
        StatisticResultInfoDTO delayStatisticResultInfoDtoRate = new StatisticResultInfoDTO(throughDtoDelay, tableFlag, yAxisIndex, hide, legendList.get(4), unitList.get(4), overTimeRate);
        delayStatisticResultInfoDtoRate.setChartType(ChartTypeEnum.LINE_CHART.getCode());

        List<StatisticResultInfoDTO> statisticResultInfoDtoList = Arrays.asList(allStatisticResultInfoDto, inTimeStatisticResultInfoDto, delayStatisticResultInfoDto, inTimeStatisticResultInfoDtoRate, delayStatisticResultInfoDtoRate);
        StatisticResultDTO statisticResultDto = new StatisticResultDTO(true, all.getTotal(), null, statisticResultInfoDtoList);
        return statisticResultDto;
    }

    /**
     * 获取新增生产单数量的ElasticAggsPojo
     *
     * @param chartResultPojo corpid, userIdIn, startTime, endTime
     * @param valueTypeEnum   数值类型
     * @return com.xbongbong.paas.elasticsearch.pojo.ElasticAggsPojo
     * @author 徐俊杰
     * @date 2019/3/14 14:13
     * @since v1.0
     */
    private ElasticAggsPojo productionOrderAdd2ElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum) throws XbbException {
        String fieldTime = "addTime";
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.boolQueryBuilder4Create(chartResultPojo, fieldTime);
        return systemChartHelp.getCount4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER, boolQueryBuilder, fieldTime);
    }

    /**
     * 获取已完成生产单数量的ElasticAggsPojo
     *
     * @param chartResultPojo corpid, userIdIn, startTime, endTime
     * @param valueTypeEnum   数值类型
     * @param script          字段间比较的条件
     * @return com.xbongbong.paas.elasticsearch.pojo.ElasticAggsPojo
     * @author 徐俊杰
     * @date 2019/3/26 9:24
     * @since v1.0
     */
    private ElasticAggsPojo productionOrderComplete2ElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum, Script script) throws XbbException {
        String fieldTime = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.PLAN_TIME);
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.productionOrderQuery4Complete(chartResultPojo, script);
        return systemChartHelp.getCount4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER, boolQueryBuilder, fieldTime);
    }

    /**
     * 获取产品Id--成品入库总成本map
     *
     * @param chartResultPojo      corpid
     * @param productionOrderIdSet 生产单id集合
     * @return java.util.Map<java.lang.Long   ,   java.lang.Double>
     * @throws XbbException 获取入库单列表抛出异常
     * @author 徐俊杰
     * @date 2019/3/30 14:56
     * @since v1.0
     */
    private Map<Long, Double> getProductIdCostSumMap(ChartResultPojo chartResultPojo, Set<Long> productionOrderIdSet) throws XbbException {
        //产品Id--成品入库总成本map
        Map<Long, Double> productIdCostSumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //生产成品入库
        List<Integer> typeIn = Arrays.asList(InstockTypeEnum.FINSHED_PRODUCT_INSTOCK.getCode());
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.instockQueryByIds4Type(chartResultPojo, productionOrderIdSet, typeIn);
        //入库单id集合
        Set<Long> instockIdSet = formHelp.getDataIdList(chartResultPojo.getCorpid(), boolQueryBuilder, IndexTypeEnum.IDX_SAAS_INSTOCK);
        //防空
        instockIdSet.add(-1L);
        List<InstockProductEntity> instockProductList = formHelp.getInstockProductsCostSum(chartResultPojo, instockIdSet);
        for (InstockProductEntity instockProductEntity : instockProductList) {
            Double costSum = instockProductEntity.getCostSum();
            //增加了判空
            if (costSum != null) {
                productIdCostSumMap.put(instockProductEntity.getProductId(), costSum);
            }
        }
        return productIdCostSumMap;
    }

    /**
     * 产品id分组，产品数量之和，产品入库数量之和（根据生产单获得）
     *
     * @param boolQueryBuilder 生产单查询参数
     * @return com.xbongbong.paas.elasticsearch.pojo.ElasticAggsPojo
     * @author 徐俊杰
     * @date 2019/3/29 14:17
     * @since v1.0
     */
    private ElasticAggsPojo getProductAndProductInstockNum(BoolQueryBuilder boolQueryBuilder) throws XbbException {
        //聚合字段
        String termField = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.PRODUCT);
        String sumField = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.PRODUCT_NUM);
        String sumField2 = ProductionOrderEnum.getEsAttr4Keyword(ProductionOrderEnum.PRODUCT_INSTOCK_NUM);
        //得到聚合条件（第一层产品id，第二层同时对两个字段求和）
        TermsAggregationBuilder termsAggregationBuilder = esHelper.getTermsAggregationOrder4TwoSum(termField, sumField, sumField2);
        return esHelper.elasticAggs4DoubleTwoSum(IndexTypeEnum.IDX_SAAS_PRODUCTION_ORDER, boolQueryBuilder, termsAggregationBuilder);
    }
}
